import UIKit

public enum LinkType {
    case url(URL)
    case email(String)
    case phone(String)
    case anchor(String)
    case custom(String)
}

public protocol LinkHandlerDelegate: AnyObject {
    func linkHandler(_ handler: LinkHandler, shouldHandle link: URL) -> Bool
    func linkHandler(_ handler: LinkHandler, didHandle link: URL)
    func linkHandler(_ handler: LinkHandler, failedToHandle link: URL, error: Error)
}

public class LinkHandler {
    public weak var delegate: LinkHandlerDelegate?
    
    public static let shared = LinkHandler()
    private init() {}
    
    public func handle(_ urlString: String) {
        guard let url = URL(string: urlString) else {
            print("Invalid URL: \(urlString)")
            return
        }
        
        // 检查代理是否允许处理该链接
        guard delegate?.linkHandler(self, shouldHandle: url) != false else {
            return
        }
        
        let linkType = classify(url)
        handleLink(type: linkType)
    }
    
    private func classify(_ url: URL) -> LinkType {
        switch url.scheme?.lowercased() {
        case "mailto":
            if let email = url.absoluteString.replacingOccurrences(of: "mailto:", with: "").removingPercentEncoding {
                return .email(email)
            }
        case "tel":
            if let phone = url.absoluteString.replacingOccurrences(of: "tel:", with: "").removingPercentEncoding {
                return .phone(phone)
            }
        case "anchor":
            if let anchor = url.host {
                return .anchor(anchor)
            }
        case "http", "https":
            return .url(url)
        default:
            if url.absoluteString.hasPrefix("#") {
                return .anchor(String(url.absoluteString.dropFirst()))
            }
            return .custom(url.absoluteString)
        }
        return .url(url)
    }
    
    private func handleLink(type: LinkType) {
        switch type {
        case .url(let url):
            handleURL(url)
        case .email(let email):
            handleEmail(email)
        case .phone(let phone):
            handlePhone(phone)
        case .anchor(let anchor):
            handleAnchor(anchor)
        case .custom(let string):
            handleCustom(string)
        }
    }
    
    private func handleURL(_ url: URL) {
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url) { [weak self] success in
                guard let self = self else { return }
                if success {
                    self.delegate?.linkHandler(self, didHandle: url)
                } else {
                    let error = NSError(domain: "LinkHandlerError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to open URL"])
                    self.delegate?.linkHandler(self, failedToHandle: url, error: error)
                }
            }
        }
    }
    
    private func handleEmail(_ email: String) {
        if let url = URL(string: "mailto:\(email)") {
            handleURL(url)
        }
    }
    
    private func handlePhone(_ phone: String) {
        if let url = URL(string: "tel:\(phone)") {
            handleURL(url)
        }
    }
    
    private func handleAnchor(_ anchor: String) {
        // 处理页内锚点跳转，需要具体实现
        print("Handle anchor: \(anchor)")
    }
    
    private func handleCustom(_ string: String) {
        // 处理自定义链接类型
        print("Handle custom link: \(string)")
    }
} 